<?php
/**
 * @Plugin Name: qlwz-digg
 * @Plugin URI: http://www.94qing.com/qlwz-Digg/
 * @Plugin Description: 仿DEDECMS Digg,支持 Widget
 * @Version: 1.0.0	
 * @Author: 情留メ蚊子
 * @Author URI: http://www.94qing.com
 */

class qlwzDigg {
	public $plugin_name = 'qlwz-digg';
	public $meta_key_good = 'digg_good';
	public $meta_key_bad = 'digg_bad';
	public $cookie_name = 'qlwz_cookie';
	public $cache_key = 'qlwz_cache_key';
	public $plugin_directory;
	public $jquery_path;

	function __construct() {
		$this -> plugin_directory = get_bloginfo('wpurl') . '/' . PLUGINDIR . '/' . dirname(plugin_basename(__FILE__));
		$this -> jquery_path = get_bloginfo('wpurl') . '/wp-includes/js/jquery/jquery.js';
	} 

	function get_dig(&$the_post = null) {
		global $post;
		if (!isset($the_post)) {
			$the_post = &$post;
		} 
		$digg_good = $this -> get_good_counts($the_post);
		$digg_bad = $this -> get_bad_counts($the_post);
		$digg_he = intval(intval($digg_good) + intval($digg_bad));
		if ($digg_good < 1 && $digg_bad < 1) {
			$percent_good = 100;
			$percent_bad = 100;
		} else {
			$percent_good = $digg_good / $digg_he * 100;
			$percent_bad = $digg_bad / $digg_he * 100;
			$percent_good = round($percent_good, 2);
			$percent_bad = round($percent_bad, 2);
		} 
		$code = '<!-- Digg-START -->';
		$code = '<span id="qlwz-digg"><div class="newdigg" id="newdigg">';
		$code .= '<div class="diggbox digg_good" onmousemove="this.style.backgroundPosition=\'left bottom\';" onmouseout="this.style.backgroundPosition=\'left top\';" onclick="javascript:postDigg(\'good\', ' . $the_post -> ID . ')">';
		$code .= '<div class="digg_act">顶一下</div>';
		$code .= '<div class="digg_num">(' . $digg_good . ')</div>';
		$code .= '<div class="digg_percent">';
		$code .= '<div class="digg_percent_bar"><span style="width:' . $percent_good . '%"></span></div>';
		$code .= '<div class="digg_percent_num">' . $percent_good . '%</div>';
		$code .= '</div>';
		$code .= '</div>';
		$code .= '<div class="diggbox digg_bad" onmousemove="this.style.backgroundPosition=\'right bottom\';" onmouseout="this.style.backgroundPosition=\'right top\';" onclick="javascript:postDigg(\'bad\', ' . $the_post -> ID . ')">';
		$code .= '<div class="digg_act">踩一下</div>';
		$code .= '<div class="digg_num">(' . $digg_bad . ')</div>';
		$code .= '<div class="digg_percent">';
		$code .= '<div class="digg_percent_bar"><span style="width:' . $percent_bad . '%"></span></div>';
		$code .= '<div class="digg_percent_num">' . $percent_bad . '%</div>';
		$code .= '</div>';
		$code .= '</div>';
		$code .= '</div></span>';
		$code .= '<!-- Digg-END -->';
		return $code;
	} 

	function get_good_counts(&$the_post) {
		$str_value = get_post_meta($the_post -> ID, $this -> meta_key_good, true);
		if (strlen($str_value) == 0) {
			add_post_meta($the_post -> ID, $this -> meta_key_good, 0, true);
		} 
		return intval($str_value);
	} 
	function get_bad_counts(&$the_post) {
		$str_value = get_post_meta($the_post -> ID, $this -> meta_key_bad, true);
		if (strlen($str_value) == 0) {
			add_post_meta($the_post -> ID, $this -> meta_key_bad, 0, true);
		} 
		return intval($str_value);
	} 

	function cookie_array($array) {
		foreach($array as $key => $value) {
			$result .= dechex($value) . 'S';
		} 
		return $result;
	} 

	function uncookie_array($string) {
		$array = preg_split('/S/', $string);
		foreach($array as $key => $value) {
			$array[$key] = hexdec($value);
		} 
		return $array;
	} 

	function hook_save_post(&$the_post) {
		add_post_meta($the_post -> ID, $this -> meta_key_good, 0, true);
		add_post_meta($the_post -> ID, $this -> meta_key_bad, 0, true);
	} 

	function hook_head_include() {
		echo "<!-- Digg Begin -->\n";
		echo "<script type=\"text/javascript\" src=\"{$this->jquery_path}\"></script>\n";
		echo "<script type=\"text/javascript\" src=\"{$this->plugin_directory}/digg.js\"></script>\n";
		echo "<link type=\"text/css\" rel=\"stylesheet\" href=\"{$this->plugin_directory}/digg.css\"/>\n";
		echo "<!-- Digg End -->\n";
	} 

	function filter_the_content($content) {
		global $post;
		if ($post -> post_type == "post") {
			if (is_single()) {
				$digg_code = $this -> get_dig($post);
				$content = $content . $digg_code;
			} 
		} 
		return $content;
	} 

	function ajax_process() {
		if (isset($_POST['postid'])  && ($_POST['type'] == "good" || $_POST['type'] == "bad")) {
			$postid = intval($_POST['postid']);
			$the_post = get_post($postid);
			if (isset($_COOKIE[$this -> cookie_name])) {
				$cookie = $this -> uncookie_array(stripslashes($_COOKIE[$this -> cookie_name]));
			} else {
				$cookie = array();
			} 
			if (!in_array($postid, $cookie)) {
				$cookie[] = $postid;
				if ($_POST['type'] == "good") {
					update_post_meta($the_post -> ID, $this -> meta_key_good, $this -> get_good_counts($the_post) + 1);
					wp_cache_delete($this -> cache_key);
				} elseif ($_POST['type'] == "bad") {
					update_post_meta($the_post -> ID, $this -> meta_key_bad, $this -> get_bad_counts($the_post) + 1);
					wp_cache_delete($this -> cache_key);
				} else {
					exit("请勿非法提交！");
				} 
				setcookie($this -> cookie_name, $this -> cookie_array($cookie), time() + 3600 * 24 * 7);
				echo $this -> get_dig($the_post);
				exit();
			} else {
				exit('您已经顶过该日志，请不要重复顶日志！');
			} 
		} 
	} 
} 

class Digg_Widget extends WP_Widget {
	function Digg_Widget() {
		$widget_ops = array('description' => '显示顶得最多的文章。');
		$this -> WP_Widget('qlwz-digg', "顶得最多", $widget_ops);
	} 
	function widget($args, $instance) {
		extract($args);
		$title = apply_filters('widget_title', esc_attr($instance['title']));
		$type = esc_attr($instance['type']);
		$mode = esc_attr($instance['mode']);
		$limit = intval($instance['limit']);
		$chars = intval($instance['chars']);
		$cat_ids = explode(',', esc_attr($instance['cat_ids']));
		echo $before_widget . $before_title . $title . $after_title;
		echo '<ul>' . "\n";
		$digg_instance = new qlwzDigg();
		echo get_list(10);
		echo '</ul>' . "\n";
		echo $after_widget;
	} 
	function update($new_instance, $old_instance) {
		if (!isset($new_instance['submit'])) {
			return false;
		} 
		$instance = $old_instance;
		$instance['title'] = strip_tags($new_instance['title']);
		return $instance;
	} 
	function form($instance) {
		global $wpdb;
		$instance = wp_parse_args((array) $instance, array('title' => "顶得最多"));
		$title = esc_attr($instance['title']);
		?>
		<p>
			<label for="<?php echo $this -> get_field_id('title');?>">标题： <input class="widefat" id="<?php echo $this -> get_field_id('title');?>" name="<?php echo $this -> get_field_name('title');?>" type="text" value="<?php echo $title;?>" /></label>
		</p>
		<input type="hidden" id="<?php echo $this -> get_field_id('submit');?>" name="<?php echo $this -> get_field_name('submit');?>" value="1" />
	<?php
	} 
} 

$digg_instance = new qlwzDigg();
add_action('save_post', array(&$digg_instance, 'hook_save_post'));
add_action('wp_head', array(&$digg_instance, 'hook_head_include'));
add_filter('the_content', array(&$digg_instance, 'filter_the_content'));
add_action('widgets_init', 'widget_Digg_init');
function widget_Digg_init() {
	register_widget('Digg_Widget');
} 
$digg_instance -> ajax_process();
if (!function_exists('get_list')) {
function get_list($limit = 10) {
	global $wpdb;
	$records = $wpdb -> get_results("SELECT P.*, M.meta_value FROM $wpdb->posts P JOIN $wpdb->postmeta M ON P.ID = M.post_id WHERE M.meta_key = 'digg_good' AND CAST(M.meta_value AS UNSIGNED) > 0 AND P.post_type='post' ORDER BY CAST(M.meta_value AS UNSIGNED) DESC LIMIT $limit");
	$code = "";
	if ($records) {
		foreach($records as $record) {
			$code .= '<li><a href="' . get_permalink($record -> ID) . '" title="' . $record -> post_title . ' 被顶' . $record -> meta_value . '次">' . $record -> post_title . '[' .$record -> meta_value . ']</a></li>';
		} 
	} else {
		$code = '<li>没有顶过的日志</li>';
	} 
	return $code;
}
} 
?>